package com.cw.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.common.api.Response;
import com.cw.common.method.SendCardMsg;
import com.cw.constant.Constants;
import com.cw.dto.*;
import com.cw.entity.*;
import com.cw.mapper2.*;
import com.cw.service.ILJysqdxxService;
import com.cw.service.ILJysqdxxXmmxService;
import com.cw.service.ILJytmxxService;
import com.cw.service.RjbfCenterService;
import com.cw.util.*;
import com.cw.vo.ResultRjszVO;
import com.cw.vo.ThisIiPrepayinRJVO;
import com.cw.vo.ViewRJSSVO;
import com.cw.vo.rjszVO;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@Service
public class RjbfCenterServiceImpl extends ServiceImpl<RjbfCenterMapper, VYqBrdjxx> implements RjbfCenterService {

    @Autowired
    private ILJysqdxxService ilJysqdxxService;

    @Autowired
    private ILJytmxxService ilJytmxxService;

    @Autowired
    private ILJysqdxxXmmxService ilJysqdxxXmmxService;

    @Autowired
    private PatientBedMiddleRjszMapper patientBedMiddleRjszMapper;

    @Autowired
    private PatientBedMiddleRjszServiceImpl patientBedMiddleRjszService;

    @Autowired
    private ThisIiPrepayinMapper thisIiPrepayinMapper;

    @Autowired
    private WeChatLogMapper weChatLogMapper;

    @Autowired
    private TelMessageMapper telMessageMapper;

    @Autowired
    private MqLogMapper mqLogMapper;

    @Autowired
    private REmployeeMapper rEmployeeMapper;

    private MQMsg mqMsg = new MQMsg();

    private static ReentrantLock lock = new ReentrantLock();

    @Override
    public PageInfo<VRJSZ> getVYqBrdjxxRJSSPagesInfo(VYqBrdjxxCondition condition) {
        List<VRJSZ> resultList = baseMapper.getVYqBrdjxxsRJSS(condition);
        return PageHelperTool.excutePageInfo(resultList, condition.getPageNum(), condition.getPageSize());
    }

    @Override
    public VYqBrdjxxVeiwDTO getRJSSVYqBrdjxx(VyqBrdjxxVeiwCondition condition) {
        if (condition != null && condition.getPreid() < 0) {
            return new VYqBrdjxxVeiwDTO();
        }
        //检验组套集合
        List<String> doctrequestnos = new ArrayList<>();
        //要检验项目集合
        List<String> ZIDComboList = new ArrayList<>();
        VYqBrdjxxVeiwDTO vYqBrdjxxVeiwDTO = new VYqBrdjxxVeiwDTO();
        //基本信息
        VYqBrdjxx vYqBrdjxx = baseMapper.getRjbfCenterInfo(condition.getPreid());

        vYqBrdjxxVeiwDTO.setVYqBrdjxx(vYqBrdjxx);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String yysj = vYqBrdjxx.getYysj();
            if (StringUtil.isNotEmpty(yysj)) {
                vYqBrdjxx.setYysj(simpleDateFormat.format(simpleDateFormat.parse(yysj)));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //处方号
        String clinicCode = vYqBrdjxx.getClinicCode();

        //检验明细列表
        vYqBrdjxxVeiwDTO.setLJysqdxxes(ilJysqdxxService.getLJysqdxxsByDorctrequestno(clinicCode));
        List<LJysqdxx> LJysqdxxList = vYqBrdjxxVeiwDTO.getLJysqdxxes();

        if (!CollectionUtil.isEmpty(LJysqdxxList)) {
            for (LJysqdxx item : LJysqdxxList) {
                List<String> doctrequestnoList = new ArrayList<>();
                doctrequestnoList.add(item.getDoctrequestno());
//                根据门诊号去查患者要做的那些检验组套
                List<LJytmxx> listFinish = ilJytmxxService.getExaminaimCodeByDoctrequestno(doctrequestnoList);
//                Examinaimcode就是后面的ZTID,这里是拿到她做完的ZTID
                List<String> ZIDFinishList = listFinish.stream()
                        .map(t -> t.getExaminaimcode())
                        .distinct()
                        .collect(Collectors.toList());
//                查询DOCTREQUESTNO这个检验单号,跟每个检验项目的ZTID,还有PATIENTID门诊号
                List<LJysqdxxXmmx> list = ilJysqdxxXmmxService.getLJysqdxxXmmxByDoctrequestnos(item.getDoctrequestno());
//                这里拿出所有要做的检验项目的ZTID
                ZIDComboList = list.stream().map(t -> t.getZtid().toString()).distinct().collect(Collectors.toList());
//                这里有特殊处理,因为数据库里EXAMINAIMCODE这个字段,就是它的ZTID会有例如“9790^11232^”这种三角符号的出现，要对它进行分割，才能去判断对比
                String strZIDFinish = String.join("", ZIDFinishList);
                List<String> splitZIDFinishList = Arrays.asList(strZIDFinish.split("\\^"));//这里有检验项合并的情况,所以增加了此操作
                String doProcess = "0";
                if (!splitZIDFinishList.get(0).equals("")) {
                    doProcess = String.valueOf(splitZIDFinishList.size());
                }

                item.setJyProcess(String.join("/", doProcess, String.valueOf(ZIDComboList.size())));
                //比较处理,如果它做了,那么ZTID是可以对应上的，那就是true，如果对应不上就是false
                boolean isTrue = true;
                for (String citem : ZIDComboList) {
                    if (!strZIDFinish.contains(citem)) {
                        isTrue = false;
                        break;
                    }
                }
//               对上的打钩
                item.setJyPass(isTrue);
            }
        }


        //检查报告列表
//          SELECT *FROM  ER_APPLY_OUT
//	WHERE BRMZH = '0005582427'   要检查项目的退费跟缴费的状态就去查这段SQL, BRMZH是患者门诊号
        vYqBrdjxxVeiwDTO.setErApplyOuts(vYqBrdjxx.getErApplyOuts());

        String idenno = vYqBrdjxx.getIdenno();
        //塞入历史状态信息
        if (StringUtil.isNotEmpty(idenno)) {
            vYqBrdjxxVeiwDTO.setHistoryState(getHistoryState(idenno));
        }

        return vYqBrdjxxVeiwDTO;
    }

    /**
     * 取消预约
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response delPatientBed(String id, String operName) {
        try {
            //根据床位id和患者id获取中间表信息
            PatientBedMiddleRjbf info = patientBedMiddleRjszMapper.selectById(id);
            if (info == null) {
                return new Response(500, "取消失败，该患者没有预约记录");
            }
            //修改状态
            info.setState("0");
            if (StringUtil.isEmpty(operName)) {
                info.setOpenName(HttpUtil.getRequestHeaderInfo(Constants.USER_NAME) + "取消预约");
            } else {
                info.setOpenName(operName + "取消预约");
            }
            info.setOperTime(LocalDateTime.now());
            Integer del = patientBedMiddleRjszMapper.updateById(info);

        } catch (Exception ex) {
            return new Response(200, "取消失败");
        }
        return new Response(200, "取消成功");
    }

    @Override
    public Response updatePatientBed(String id) {
        try {

            //根据床位id和患者id获取中间表信息
            PatientBedMiddleRjbf info = patientBedMiddleRjszMapper.selectById(id);
            if (info == null) {
                return new Response(500, "输注失败，该患者没有预约记录");
            }
            //修改状态
            info.setState("2");
            Integer update = patientBedMiddleRjszMapper.updateById(info);

        } catch (Exception ex) {
            return new Response(500, "输注失败");
        }
        return new Response(200, "输注完成");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response addPatientBed(RjszDTO entity) {
        lock.lock();
        try {
            //判断是否被预约
            List<PatientBedMiddleRjbf> patientBedNew = patientBedMiddleRjszMapper.selectList(new LambdaQueryWrapper<>(
                    new PatientBedMiddleRjbf()).eq(PatientBedMiddleRjbf::getPreid, entity.getPreid())
                    .eq(PatientBedMiddleRjbf::getState, "1")
                    .eq(PatientBedMiddleRjbf::getType, entity.getBedType()));
            if (CollectionUtils.isNotEmpty(patientBedNew)) {
                return new Response(500, "预约失败,该患者已预约日间手术/日间输注");
            }
            //根据病人PreId获取电子一体化床位申请信息
            PatientBedMiddleRjbf patientBed = new PatientBedMiddleRjbf();
            patientBed.setId(UUIDUtil.uuid());
            patientBed.setPreid(entity.getPreid());
            patientBed.setYard("1");
            patientBed.setNurseCellCode("2739");
            patientBed.setNurseCellName("二十一病区");
            patientBed.setDeptCode("1664");
            patientBed.setDeptName("日间治疗中心");
            //已预约
            patientBed.setState("1");
            patientBed.setOperCode(entity.getJobnumber());
            patientBed.setOpenName(entity.getCreateBy());
            patientBed.setOperTime(LocalDateTime.now());
            patientBed.setAppointmentTime(entity.getAppoinmentTime());
            patientBed.setType(entity.getBedType());
            patientBed.setAppointmentClasses(entity.getAppointmentClasses());
            patientBed.setDocCode(entity.getDocCode());
            patientBed.setDocName(entity.getDocName());
            patientBed.setInpatientNo("");
            patientBed.setCreateTime(new Date());
            Integer insert = patientBedMiddleRjszMapper.insert(patientBed);
            //从日间患者视图中获取患者基本信息构建到ThisIiPrepayin中
            ThisIiPrepayin thisIiPrepayin = new ThisIiPrepayin();
            ViewRJSSVO rjssvo = baseMapper.getRJSSInfoByPreId(entity.getPreid());
            if (rjssvo != null) {
                thisIiPrepayin.setPreid(rjssvo.getPreid());
                thisIiPrepayin.setName(rjssvo.getName());
                thisIiPrepayin.setHomeTel(rjssvo.getHomeTel());
            }

            // 发送短信
            // 获取当前时间
            Date date = new Date();
            long diff = entity.getAppoinmentTime().getTime() - date.getTime();
            TimeUnit time = TimeUnit.DAYS;
            long diffrence = time.convert(diff, TimeUnit.MILLISECONDS);
            // 先判断预约时间距离手术时间是否小于一天，小于一天立即发送短信给患者和医生
            MsgInfo msgInfo = getMsgInfo(thisIiPrepayin, entity, 1);
            // 预约表根据病人id查询，如果存在就发送信息
            PatientBedMiddleRjbf appointmentMsg =
                    patientBedMiddleRjszMapper.selectByPreid(Long.parseLong(msgInfo.getPreid()
                    .toString()));
            //发送MQ   （这个是发给个人的）
            setMsg(msgInfo, appointmentMsg);
            if (diffrence <= 1) {
                // 发送到医生企业微信
                //发送企业微信
                if (msgInfo.getWechatAccountCode() != null && !msgInfo.getWechatAccountCode().isEmpty()) {
                    //企业微信返回josn消息体
                    //调用post发送企业微信消息
                    WeChatLog weChatLog = null;
                    try {
                        weChatLog = SendCardMsg.send3(msgInfo, appointmentMsg);
                    } catch (IOException e) {
                        int a = 0;
                    }
                    weChatLogMapper.insert(weChatLog);
                }
                baseMapper.updateDocSendFlag(Long.parseLong(entity.getPreid().toString()));
            }

            // 判断预约时间距离手术时间是否小于三天天，小于三天立即发送短信给患者
            if (diffrence <= 2) {
                //调用医院发送手机短信的接口
                TelMessageLog telMessageLog = SendCardMsg.sendTelMessage3(msgInfo,
                        patientBed.getAppointmentTime(),
                        patientBed.getAppointmentClasses(),
                        rjssvo,
                        0);
                telMessageMapper.insert(telMessageLog);
                baseMapper.updatePatientSendFlag(Long.parseLong(entity.getPreid().toString()));
            }
        } catch (Exception ex) {
            return new Response(500, "预约失败");
        } finally {
            lock.unlock();
        }
        return new Response(200, "预约成功");

    }

    @Override
    public ThisIiPrepayinRJVO getIiPrepayinByIdRJ(BigDecimal preid) {
        return patientBedMiddleRjszMapper.getIiPrepayinByIdRJ(preid);
    }

    @Override
    public ResultRjszVO searchRJSS() {
        ResultRjszVO resultRjszVO = new ResultRjszVO();
        String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<rjszVO> rjszVOS = patientBedMiddleRjszMapper.searchRJSS();
        rjszVOS.forEach(s -> {
            Calendar cal = Calendar.getInstance();
            cal.setTime(s.getSzrq());
            int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (week_index < 0) {
                week_index = 0;
            }
            s.setWeek(sdf.format(s.getSzrq()) + "(" + weeks[week_index] + ")");
        });
        resultRjszVO.setRjszVOS(rjszVOS);
        resultRjszVO.setTimeSlotNum(patientBedMiddleRjszMapper.searchCount(1));
        return resultRjszVO;
    }

    @Override
    public ResultRjszVO searchRJSZ() {
        ResultRjszVO resultRjszVO = new ResultRjszVO();
        String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<rjszVO> rjszVOS = patientBedMiddleRjszMapper.searchRJSZ();
        rjszVOS.forEach(s -> {
            Calendar cal = Calendar.getInstance();
            cal.setTime(s.getSzrq());
            int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (week_index < 0) {
                week_index = 0;
            }
            s.setWeek(sdf.format(s.getSzrq()) + "(" + weeks[week_index] + ")");
        });
        resultRjszVO.setRjszVOS(rjszVOS);
        resultRjszVO.setTimeSlotNum(patientBedMiddleRjszMapper.searchCount(4));
        return resultRjszVO;
    }

    @Override
    public PageInfo<ThisIiPrepayin> getHandworkPrepayin(HandworkPrepayinDto handworkPrepayinDto) {
        List<ThisIiPrepayin> resultList = baseMapper.getHandworkPrepayin(handworkPrepayinDto);
        List<String> operCodeList = resultList.stream().map(ThisIiPrepayin::getOperCode).collect(Collectors.toList());
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(operCodeList)) {
            List<ThisIiPrepayin> docList = baseMapper.getDoctorNameByCode(operCodeList);

            resultList.stream().forEach(r -> {
                ThisIiPrepayin thisIiPrepayin = docList.stream()
                        .filter(d -> d.getOperCode().equals(r.getOperCode()))
                        .findFirst()
                        .orElse(null);
                if (thisIiPrepayin != null) {
                    r.setDoctName(thisIiPrepayin.getDoctName());
                } else {
                    r.setDoctName("admin");
                }
            });
        }
        return PageHelperTool.excutePageInfo(resultList,
                handworkPrepayinDto.getPageNum(),
                handworkPrepayinDto.getPageSize());
    }

    @Override
    public void getVYqBrdjxxRJSSDownLoad(VYqBrdjxxCondition condition) {
        try {
            List<VRJSZ> sourceList = baseMapper.getVYqBrdjxxsRJSS(condition);
            sourceList.forEach(item -> {
                if ("2".equals(item.getSex())) {
                    item.setSex("女");
                } else {
                    item.setSex("男");
                }
                if ("1".equals(item.getBedType())) {
                    item.setBedType("日间手术");
                } else {
                    item.setBedType("日间输注");
                }
                //状态
                if ("0".equals(item.getState())) {
                    item.setState("取消登记");
                } else if ("1".equals(item.getState())) {
                    item.setState(" 已预约");
                } else if ("2".equals(item.getState())) {
                    item.setState(" 已完成");
                } else {

                }
                //来源类型
                if ("1".equals(item.getSourceType())) {
                    item.setSourceType("住院");
                } else if ("2".equals(item.getSourceType())) {
                    item.setSourceType("门诊");
                } else {

                }

            });

            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //设置背景颜色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            //设置头字体
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 10);
            headWriteFont.setBold(true);
            headWriteCellStyle.setWriteFont(headWriteFont);
            //设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

            //内容策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(headWriteCellStyle,
                    contentWriteCellStyle);

            ServletRequestAttributes servletRequestAttributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = servletRequestAttributes.getResponse();
            String name = String.valueOf(System.currentTimeMillis());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(name, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");

            // 根据用户传入字段  set是删除字段
            Set<String> excludeColumnFiledNames = new HashSet<String>();
            excludeColumnFiledNames.add("Id");
            excludeColumnFiledNames.add("preid");
            excludeColumnFiledNames.add("deptName");
            excludeColumnFiledNames.add("yblx");
            excludeColumnFiledNames.add("createTime");
            excludeColumnFiledNames.add("clinicCode");
            excludeColumnFiledNames.add("medicalInsuranceFlag");
            excludeColumnFiledNames.add("bedNo");
            excludeColumnFiledNames.add("doit");
            excludeColumnFiledNames.add("total");
            Map<String, List<RowRangeDto>> map = ExcelUtil.reflectionAddMerStrategy(sourceList);
            EasyExcel.write(response.getOutputStream(), VRJSZ.class)
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(new BizMergeStrategy(map))
                    .excludeColumnFiledNames(excludeColumnFiledNames)
                    .sheet("sheet")
                    .doWrite(sourceList);
        } catch (Exception ex) {
            int a = 1;
        }

    }

    @Override
    public Response cancellation(String preId) {
        LambdaUpdateWrapper<PatientBedMiddleRjbf> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PatientBedMiddleRjbf::getPreid, preId)
                .eq(PatientBedMiddleRjbf::getState, "1")
                .set(PatientBedMiddleRjbf::getState,"0");
        boolean update = patientBedMiddleRjszService.update(updateWrapper);
        if (!update){
            return new Response(500, "取消失败");
        }
        return new Response(200, "取消成功");
    }

    public MsgInfo getMsgInfo(ThisIiPrepayin patientInfo, RjszDTO entity, int flag) {
        MsgInfo info = new MsgInfo();
        info.setName(patientInfo.getName());
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        String date = ft.format(entity.getAppoinmentTime());
        info.setAppointMentDate(date);
        info.setAppointmentTime(entity.getAppointmentClasses());
        info.setLinkmanTel(patientInfo.getHomeTel());
        info.setPreid(entity.getPreid());
        // 企业微信编号
        LambdaQueryWrapper<REmployee> lambdaQueryEmployeeWrapper = new LambdaQueryWrapper<>();
        lambdaQueryEmployeeWrapper.eq(REmployee::getEmplCode, entity.getJobnumber());
        REmployee retREmployee = rEmployeeMapper.selectOne(lambdaQueryEmployeeWrapper);
        //            info.setWechatAccountCode("100472");  --胡处  测试用
        if (retREmployee != null) {
            info.setWechatAccountCode(retREmployee.getXgzh());
        }

        if (flag == 0) {
            info.setTitle("日间病房床位取消预约成功");
            info.setResult("已取消");
        } else {
            info.setTitle("日间病房床位预约成功");
            info.setResult("已预约");
        }
        return info;
    }

    public void setMsg(MsgInfo msgInfo, PatientBedMiddleRjbf appointmentMsg) {
        if (appointmentMsg != null) {
            // 设定用户
            mqMsg.setUserName("S01");
            // 设定密码
            mqMsg.setPassword("123456");
            // 设定通道池
            mqMsg.setQueueManagerName("QMGR.P01");
            // 设定消息频道
            mqMsg.setChannel("PS35035");
            // 设定姓名
            mqMsg.setPatName(msgInfo.getName());
            // 索引号
            mqMsg.setPatIndexNo(msgInfo.getPreid().toString());
            mqMsg.setMsgTitle(msgInfo.getTitle());
            // 医生姓名工号
            mqMsg.setReciveCode(appointmentMsg.getDocCode());
            mqMsg.setReciveName(appointmentMsg.getDocName());
            // 预约时间
            Date appointmentTime = appointmentMsg.getAppointmentTime();
            String appointmentClasses = appointmentMsg.getAppointmentClasses();
            // 获取年  月  日
            ZoneId timeZone = ZoneId.systemDefault();
            LocalDate getDate = appointmentTime.toInstant().atZone(timeZone).toLocalDate();
            // 年
            int year = getDate.getYear();
            // 月
            int month = getDate.getMonthValue();
            // 日
            int day = getDate.getDayOfMonth();

            //发给个人
            mqMsg.setMessageType("2");
            mqMsg.setMsgContent(msgInfo.getName() + "先生/女士" + year + "年" + month + "月" + day + "日是您预约来我院治疗的日子，请您于" + year + "年" + month + "月" + day + "日" + appointmentClasses + "根据医生电话交代的时间，带好住院证、检查等报告、门诊缴费发票，到住院部2-3号楼之间13号楼住院服务中心办手续，然后到2号楼2层21病区：日间治疗中心护士站。如有特殊情况请联系您的主治医师或日间病房咨询电话：0512-67784215。\n" + "入院需知：\n" + "1.需要上麻醉者请确认已完成麻醉科门诊评估后再入院，局麻手术者无需麻醉门诊评估。\n" + "2.需要上麻醉者手术前一日22点之后禁食禁水，局麻手术者一般可正常饮食，具体以手术医生电话通知为准；\n" + "3.特别提醒：如果手上有美甲请在来手术之前去除或者起码去除不同手的2个美甲。\n" + "4.手术当天需家属一人陪护，请不要携带任何贵重物品，更不要佩带任何首饰。\n" + "感谢您的理解与配合！");
            mqMsg.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            // 设定发送者工号
            mqMsg.setSenderCode(msgInfo.getEmplCode());
            // 设定发送者姓名
            mqMsg.setSenderName(msgInfo.getEmplName());
            // 设定床位号
            mqMsg.setBedNum(msgInfo.getBedNum());
            // 设定科室编号
            mqMsg.setDeptCode(msgInfo.getDeptCode());
            // 设定科室名称
            mqMsg.setDeptName(msgInfo.getDeptName());
            // 病区代码
            mqMsg.setWardCode(msgInfo.getNurseCellCode());
            // 设定病区名称
            mqMsg.setWardName(msgInfo.getNurseCellName());
            // 设定院区编号
            mqMsg.setHospDistrictCode(msgInfo.getYard());
            // 设定院区
            mqMsg.setHostDistrictName(msgInfo.getYardName());
            mqMsg.setReciveCode(appointmentMsg.getDocCode());
            mqMsg.setReciveName(appointmentMsg.getDocName());
            String xmlString = mqMsg.createXMLString(mqMsg);

            MqLog mqLog = new MqLog();
            String uuid = UUIDUtil.uuid();
            mqLog.setId(uuid);
            mqLog.setRequestMsg(xmlString);
            mqLog.setRequestDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            mqLog.setSenderCode(msgInfo.getEmplCode());
            mqLog.setSenderName(msgInfo.getEmplName());

            String msgId = mqMsg.putMsg(xmlString);
            System.out.println(msgId);
            mqLog.setMsgId(msgId);
            if (msgId != "") {
                mqLog.setResponseType("success");
            } else {
                mqLog.setResponseType("fail");
            }
            mqLogMapper.insert(mqLog);
        }
    }

    private List<VYqBrdjxx> getHistoryState(String idenNo) {

        LambdaQueryWrapper<VYqBrdjxx> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(VYqBrdjxx::getIdenno, idenNo);
        lambdaQueryWrapper.select(VYqBrdjxx::getYyrq, VYqBrdjxx::getCyrq, VYqBrdjxx::getRyrq, VYqBrdjxx::getQxsj);
        lambdaQueryWrapper.orderByDesc(VYqBrdjxx::getYyrq);
        return list(lambdaQueryWrapper);
    }

}
